package ch.zbw.timeline.presentation.model;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import ch.zbw.timeline.domain.Holiday;
import ch.zbw.timeline.presentation.helper.Formatter;

/**
 * TableModel for the holidays
 * 
 * @author Daniel Stefanovic
 * @version 18.01.2012
 * 
 */
public class HolidayTableModel extends DefaultTableModel {

	private static final String[] HEADER = { "", "Datum", "Bezeichnung" };
	private List<Holiday> holidays;

	/**
	 * Constructor
	 */
	public HolidayTableModel() {
		this.addTableModelListener(new CheckBoxTableModelListener());
	}

	/**
	 * Get the number of Columns
	 */
	public int getColumnCount() {
		return HEADER.length;
	}

	/**
	 * Set the list of holidays
	 * 
	 * @param holidays list of holidays
	 */
	public void setHolidays(List<Holiday> holidays) {
		this.holidays = holidays;

		loadHolidays();
	}

	/**
	 * Returns the list of holidays
	 * 
	 * @return list of holidays
	 */
	public List<Holiday> getHolidays() {
		return holidays;
	}


	
	/**
	 * Load the holidays into table
	 */
	private void loadHolidays() {
		// clear detailTableModel
		int row = this.getRowCount();
		for (int counter = (row) - 1; counter > -1; counter--) {
			this.removeRow(counter);
		}

		if (holidays != null) {
			for (Holiday h : holidays) {
				addRow(new Object[] { h.isActive(), Formatter.INSTANCE.formatDate(h.getDateOfHoliday().getTime()),
						h.getFormula().getDescription() });
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * @see javax.swing.table.DefaultTableModel#getColumnName(int)
	 */
	@Override
	public String getColumnName(int column) {
		return HEADER[column];
	}

	/*
	 * (non-Javadoc)
	 * @see javax.swing.table.DefaultTableModel#isCellEditable(int, int)
	 */
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return (columnIndex == 0);
	}

	/*
	 * (non-Javadoc)
	 * @see javax.swing.table.AbstractTableModel#getColumnClass(int)
	 */
	@Override
	public Class<?> getColumnClass(int column) {
		if (column == 0) {
			return Boolean.class;
		}
		return super.getColumnClass(column);
	}

	/**
	 * Listener for the checkboxes
	 */
	private class CheckBoxTableModelListener implements TableModelListener {

		public void tableChanged(TableModelEvent e) {
			if (e.getType() == TableModelEvent.UPDATE)
		    {
		        int row = e.getFirstRow();
		        int column = e.getColumn();

		        if (column == 0)
		        {
		            TableModel model = (TableModel)e.getSource();
		            Boolean value = (Boolean)model.getValueAt(row, column);

		            holidays.get(row).setActive(value.booleanValue());

		        }
		    }

		}
	}

}
